﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using RuoVea.DynamicWebApi;
using RuoVea.ExDto;
using RuoVea.ExEnum;
using RuoVea.ExSugar;
using RuoVea.ExSugar.Entity;
using RuoVea.ExUtil;
using RuoVea.OmiApi.Article.Entitys;
using RuoVea.OmiApi.Article.Service.Dto;
using SqlSugar;
using exDtoi18n = RuoVea.ExDto.Language.i18n;
using exUtili18n = RuoVea.ExUtil.Language.i18n;

namespace RuoVea.OmiApi.Article.Service;

/// <summary>
/// 文章评论 🔷
/// </summary>
[ApiExplorerSettings(GroupName = "art")]
public class CommentService : IApplicationService
{
    private readonly SugarRepository<ArtComment> _thisRepository;
    private readonly ISqlSugarClient _sqlSugarClient;

    /// <summary>
    /// 参数配置表
    /// </summary>
    /// <param name="thisRepository"></param>
    /// <param name="sqlSugarClient"></param>
    public CommentService(SugarRepository<ArtComment> thisRepository, ISqlSugarClient sqlSugarClient)
    {
        _thisRepository = thisRepository;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 查询所有/分页🔹
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public virtual async Task<PageResult<CommentDto>> GetPagesAsync([FromQuery] CommentParam data)
    {
        var query = await _thisRepository.AsQueryable()
            .Includes(u => u.Children)
            .Where(u => u.ArticleId == data.ArticleId && u.PId == 0)
            .WhereIF(data.Creator > 0, u => u.Creator == data.Creator)
            .WhereIF(data.Status != null, u => u.Status == data.Status)
            .OrderBy(u => u.CreateTime)
            .ToPageAsync<ArtComment, CommentDto>(data.PageNo, data.PageSize);
        return query;
    }

    /// <summary>
    /// 根据主键查询🔹
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public virtual async Task<CommentDto> GetDataAsync([FromQuery] EntityBaseId data)
    {
        var model = await _thisRepository.AsQueryable().Where(x => x.Id == data.Id).FirstAsync();
        return model.Adapt<CommentDto>();
    }

    /// <summary>
    /// 添加🔹
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public virtual async Task<bool> AddDataAsync([FromBody] CommentDto data)
    {
        if (data == null)
            throw new ArgumentException(ErrorEnum.D1504.GetDescription(exDtoi18n.ResourceManager));

        if (data.ArticleId <= 0)
            throw new AggregateException(string.Format(exUtili18n.invalidintegerformat, "ArticleId"));

        if (data.Creator <= 0)
            throw new AggregateException(string.Format(exUtili18n.invalidintegerformat, "Creator"));

        if (data.Content.IsNullOrWhiteSpace())
            throw new AggregateException(string.Format(exUtili18n.fieldisrequired, "Content"));

        var dictType = data.Adapt<ArtComment>();

        var result = await _sqlSugarClient.Ado.UseTranAsync(async () =>
        {

            // 章评论数+1
            await _sqlSugarClient.Updateable<ArtArticle>()
                   .SetColumns(a => a.CommentCount == a.CommentCount + 1)
                   .Where(a => a.Id == dictType.ArticleId )
                   .ExecuteCommandAsync();
            return await _thisRepository.InsertAsync(dictType);
        });

        if (!result.IsSuccess)
            throw new Exception(exDtoi18n.failed + result.ErrorMessage);

        return result.IsSuccess;
    }

    /// <summary>
    /// 修改🔹
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public virtual async Task UpdateDataAsync([FromBody] CommentDto data)
    {
        if (data == null)
            throw new ArgumentException(ErrorEnum.D1504.GetDescription(exDtoi18n.ResourceManager));

        if (data.Id <= 0)
            throw new AggregateException(string.Format(exUtili18n.invalidintegerformat, "Id"));

        if (data.ArticleId <= 0)
            throw new AggregateException(string.Format(exUtili18n.invalidintegerformat, "ArticleId"));

        if (data.Creator <= 0)
            throw new AggregateException(string.Format(exUtili18n.invalidintegerformat, "Creator"));

        if (data.Content.IsNullOrWhiteSpace())
            throw new AggregateException(string.Format(exUtili18n.fieldisrequired, "Content"));

        var isExist = await _thisRepository.IsAnyAsync(u => u.Id == data.Id);
        if (!isExist) throw new ArgumentException(ErrorEnum.D1002.GetDescription(exDtoi18n.ResourceManager));
        var dictType = data.Adapt<ArtComment>();

        await _thisRepository.UpdateAsync(dictType);
    }

    /// <summary>
    /// 删除🔹
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpDelete]
    public virtual async Task DeleteDataAsync([FromBody] EntityBaseId data)
    {
        if (data == null)
            throw new ArgumentException(ErrorEnum.D1504.GetDescription(exDtoi18n.ResourceManager));

        data.Check();

        var dictType = await _thisRepository.GetFirstAsync(u => u.Id == data.Id);
        if (dictType == null) throw new ArgumentException(ErrorEnum.D1002.GetDescription(exDtoi18n.ResourceManager));
        var result = await _sqlSugarClient.Ado.UseTranAsync(async () =>
        {
            if (dictType.IsDelete == IsDelete.Y)
            {
                // 物理删除
                await _thisRepository.DeleteByIdAsync(data.Id);
            }
            else
            {
                dictType.IsDelete = IsDelete.Y;

                // 文章评论数-1
                await _sqlSugarClient.Updateable<ArtArticle>()
                   .SetColumns(a => a.CommentCount == a.CommentCount - 1)
                   .Where(a => a.Id == dictType.ArticleId && a.CommentCount>0)
                   .ExecuteCommandAsync();

                await _thisRepository.UpdateAsync(dictType);
            }
        });
    }
}
